package com.tyl.svolatile;

import java.util.concurrent.atomic.AtomicInteger;

public class volatile2 {
    private  volatile static AtomicInteger sum=new AtomicInteger();
    //volatile 不保证有原子性，线程执行时会有别的线程加进来
    //synchronize使用后就依次执行
    private  static void add(){
        // sum++;//不是原子性操作
        sum.getAndIncrement();//AndIncrement+1方法
    }
    public  static  void main(String[] args) {
        for (int i = 0; i < 20; i++) {
             new  Thread(()->{
                for (int j = 0; j < 1000; j++) {
                    add();
                }
            }).start();
        }
        while (Thread.activeCount()>2){
            Thread.yield();
        }
        System.out.println(Thread.currentThread().getName()+" "+sum);
    }
}
